"""
系统指标API
"""

from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models import SystemMetrics, User, Appointment, Resource, SchedulingResult
from app.api import api_bp
from datetime import datetime, timedelta

@api_bp.route('/metrics/overview', methods=['GET'])
@jwt_required()
def get_metrics_overview():
    """获取系统指标概览"""
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    # 权限检查
    if user.role not in ['admin', 'doctor']:
        return jsonify({'error': '无权限访问'}), 403
    
    # 获取最近24小时的数据
    end_time = datetime.now()
    start_time = end_time - timedelta(hours=24)
    
    # 预约统计
    total_appointments = Appointment.query.count()
    today_appointments = Appointment.query.filter(
        Appointment.scheduled_time >= start_time
    ).count()
    
    # 资源统计
    total_resources = Resource.query.count()
    available_resources = Resource.query.filter_by(status='available').count()
    
    # 调度性能
    recent_schedules = SchedulingResult.query.filter(
        SchedulingResult.created_at >= start_time
    ).all()
    
    avg_utilization = 0
    avg_wait_time = 0
    if recent_schedules:
        avg_utilization = sum(s.resource_utilization for s in recent_schedules) / len(recent_schedules)
        avg_wait_time = sum(s.patient_wait_time for s in recent_schedules) / len(recent_schedules)
    
    return jsonify({
        'appointments': {
            'total': total_appointments,
            'today': today_appointments
        },
        'resources': {
            'total': total_resources,
            'available': available_resources,
            'utilization_rate': round(avg_utilization, 2)
        },
        'performance': {
            'avg_wait_time': round(avg_wait_time, 2),
            'scheduling_count': len(recent_schedules)
        }
    })

@api_bp.route('/metrics/trends', methods=['GET'])
@jwt_required()
def get_metrics_trends():
    """获取指标趋势"""
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    # 权限检查
    if user.role not in ['admin', 'doctor']:
        return jsonify({'error': '无权限访问'}), 403
    
    # 获取最近7天的数据
    end_date = datetime.now().date()
    start_date = end_date - timedelta(days=7)
    
    trends = []
    for i in range(7):
        date = start_date + timedelta(days=i)
        
        # 当日预约数
        appointment_count = Appointment.query.filter(
            db.func.date(Appointment.scheduled_time) == date
        ).count()
        
        # 当日资源利用率
        daily_schedules = SchedulingResult.query.filter(
            db.func.date(SchedulingResult.created_at) == date
        ).all()
        
        avg_utilization = 0
        if daily_schedules:
            avg_utilization = sum(s.resource_utilization for s in daily_schedules) / len(daily_schedules)
        
        trends.append({
            'date': date.isoformat(),
            'appointments': appointment_count,
            'utilization': round(avg_utilization, 2)
        })
    
    return jsonify(trends)

@api_bp.route('/metrics/performance', methods=['GET'])
@jwt_required()
def get_performance_metrics():
    """获取性能指标"""
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    # 权限检查
    if user.role not in ['admin', 'doctor']:
        return jsonify({'error': '无权限访问'}), 403
    
    # 获取最近30天的性能数据
    end_date = datetime.now()
    start_date = end_date - timedelta(days=30)
    
    schedules = SchedulingResult.query.filter(
        SchedulingResult.created_at >= start_date,
        SchedulingResult.created_at <= end_date
    ).all()
    
    if not schedules:
        return jsonify({'error': '没有性能数据'}), 404
    
    # 计算各项指标
    utilizations = [s.resource_utilization for s in schedules]
    wait_times = [s.patient_wait_time for s in schedules]
    fairness_scores = [s.fairness_score for s in schedules]
    execution_times = [s.execution_time for s in schedules]
    
    # 按算法分组统计
    algorithm_stats = {}
    for schedule in schedules:
        algorithm = schedule.algorithm_used
        if algorithm not in algorithm_stats:
            algorithm_stats[algorithm] = {
                'count': 0,
                'avg_utilization': 0,
                'avg_wait_time': 0,
                'avg_fairness': 0,
                'avg_execution_time': 0
            }
        
        algorithm_stats[algorithm]['count'] += 1
        algorithm_stats[algorithm]['avg_utilization'] += schedule.resource_utilization
        algorithm_stats[algorithm]['avg_wait_time'] += schedule.patient_wait_time
        algorithm_stats[algorithm]['avg_fairness'] += schedule.fairness_score
        algorithm_stats[algorithm]['avg_execution_time'] += schedule.execution_time
    
    # 计算平均值
    for algorithm in algorithm_stats:
        count = algorithm_stats[algorithm]['count']
        algorithm_stats[algorithm]['avg_utilization'] /= count
        algorithm_stats[algorithm]['avg_wait_time'] /= count
        algorithm_stats[algorithm]['avg_fairness'] /= count
        algorithm_stats[algorithm]['avg_execution_time'] /= count
    
    return jsonify({
        'overall': {
            'avg_utilization': round(sum(utilizations) / len(utilizations), 2),
            'avg_wait_time': round(sum(wait_times) / len(wait_times), 2),
            'avg_fairness': round(sum(fairness_scores) / len(fairness_scores), 2),
            'avg_execution_time': round(sum(execution_times) / len(execution_times), 2)
        },
        'algorithms': algorithm_stats
    })
